package cn.enn.smart.conf;

import cn.enn.smart.filter.MobileLoginFilter;
import cn.enn.smart.properties.EnnMobileLoginProperties;
import cn.enn.smart.provider.MobileAuthenticationProvider;
import cn.enn.smart.service.UserDetailsServiceExtension;
import cn.enn.smart.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@AutoConfigureBefore(EnnValidateCodeSecurityConfigurer.class)
public class EnnMobileLoginSecurityConfigurer extends EnnSecurityConfigurer {

	@Autowired
	private EnnMobileLoginProperties properties;

	@Autowired
	private UserDetailsServiceExtension userDetailsServiceExtension;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;

	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;

	@Autowired
	private ValidateCodeService validateCodeService;

	@Override
	public void configure(HttpSecurity http) throws Exception {

		MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider(
				userDetailsServiceExtension, passwordEncoder);
		mobileAuthenticationProvider.setValidateCodeService(validateCodeService);
		http.authenticationProvider(mobileAuthenticationProvider);

		MobileLoginFilter mobileLoginFilter = new MobileLoginFilter(properties.getProcessUrl());
		ProviderManager authenticationManager = new ProviderManager(mobileAuthenticationProvider);

		if (properties.getPostOnly() != null) {
			mobileLoginFilter.setPostOnly(properties.getPostOnly());
		}

		mobileLoginFilter.setMobileParameter(properties.getMobileParameter());
		mobileLoginFilter.setPasswordParameter(properties.getPasswordParameter());
		mobileLoginFilter.setAuthenticationManager(authenticationManager);
		mobileLoginFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
		mobileLoginFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
		http.addFilterBefore(mobileLoginFilter, UsernamePasswordAuthenticationFilter.class);
	}

}
